<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

define('CONTROL_TEXT', 1);
define('CONTROL_CHECKBOX', 2);
define('CONTROL_RADIOGROUP', 3);
define('CONTROL_SELECT', 4);
define('CONTROL_TEXTAREA', 5);

//TODO check new option for configs - 'required_if'. seems working fine. Check later.
// TODO TO THINK. Maybe would be usefull if 'required_if' would have some wildcard? 
// 		For example integer or strings or some regular expression. 

class Configuration  extends MController {

	var $object_id = null;
	var $group = null;
	var $configuration = array();

	function __construct () {
		parent::__construct();
		$this->load->model('Configurationmodel');
		$this->load->helper('url');
		$this->lang->load('configuration', 'Russian');
	}

	function index ($object_id = null, $group = null) {
		if (!$group) { 
			$group = 'user';
			if (!$object_id) { 
				return $this->user();
			}	 
		}
		
		$this->Configurationmodel->object_id = $object_id;
		$this->Configurationmodel->group = $group;
		
		$this->configuration = $this->Configurationmodel->getObjectConfigs();
		
		$this->load->helper('form');
		
		parent::display($this->load->view('configuration', array('configuration' => $this->configuration), true));
	}
	
	function user ($object_id = null) {

		if (!$object_id) { $object_id = $this->session->userdata('user_id'); }

		$this->load->helper('form');
		$this->load->library('MConfiguration');

		$sentFl = $this->input->post('submit');
		$form = $this->mconfiguration->form('user', $object_id, !$sentFl);

		if ($sentFl) {
			$errorFlag = false;
			$error = array();
			foreach ($form['inputs'] as $key => $input) {
				if ($input['required'] && !$this->input->post($key)) {
					$errorFlag = true;
					$error[] = $key;
				}
				$this->Configurationmodel->configs[$key]->value = $inputs[$key] = $this->input->post($key);
			}
			
			if ($errorFlag) {
				$this->setMessage($this->lang->line('configuration_error_filling_form'), 'error');
				$this->setMessage(array('error' => $error, 'inputs' => $inputs), 'form');
				redirect($this->uri->uri_string());
				return ;
			}
			
			if ($this->Configurationmodel->save()) {
				$this->setMessage($this->lang->line('configuration_save_success'), 'Success');
			} else {
				$this->setMessage($this->lang->line('configuration_save_failed'), 'Error');
			}
			redirect('/configuration');
		} else {	
			$this->load->helper('form');
			$form['name'] = 'user';

			$form['open_tag'] = form_open($this->uri->uri_string());
			$form['close_tag'] = form_close();
			
			$form['controls'] = array(
				'submit' => form_submit('submit', $this->lang->line('configuration_save_label')), 
				'cancel' => form_submit('cancel', $this->lang->line('configuration_cancel_label')));
			
			$content = $this->load->view('configuration', $form, true);
			parent::display($content);
		}
	}

	function admin ($group = null) {

		if ($group) { $this->Configurationmodel->group = $group; }
		
		if ($this->input->post('submit')) {
			
			$form = $this->getConfigurationForm(false);
			$errorFlag = false;
			$error = array();
			foreach ($form['inputs'] as $key => $input) {
				if ($input['required'] && !$this->input->post($key)) {
					$errorFlag = true;
					$error[] = $key;
				}
				$this->configuration[$key]->value = $inputs[$key] = $this->input->post($key);
			}
			
			if ($errorFlag) {
				$this->setMessage($this->lang->line('configuration_error_filling_form'), 'error');
				$this->setMessage(array('error' => $error, 'inputs' => $inputs), 'form');
				redirect($this->uri->uri_string());
				return ;
			} else {
				$this->Configurationmodel->configs = $this->configuration;
			}
			
			if ($this->Configurationmodel->save()) {
				$this->setMessage($this->lang->line('configuration_save_success'), 'Success');
			} else {
				$this->setMessage($this->lang->line('configuration_save_failed'), 'Error');
			}
			redirect('/configuration');
		} else {
			$this->load->helper('form');
			
			$filter = $this->session->userdata(__CLASS__ . '.' . __FUNCTION__ . '.filter');
			$filter = $filter ? $filter : array();
			
			$this->load->library('pagination');
			$pgConfig = array('base_url' => '/configuration/admin/', 
							  'per_page' => 10, 
							  'total_rows' => $this->Configurationmodel->count_configs($filter));
			
			$this->pagination->initialize($pgConfig);
			$pagination = $this->load->view('pagination', array('pagination' => $this->pagination->create_links()), true);
			
			$configs = $this->Configurationmodel->getConfigs($filter, $this->pagination->per_page, ($this->pagination->cur_page - 1) * $this->pagination->per_page);
			
			$data = array('filter' => $this->load->view('filter', $this->configFilterForm($filter), true), 
						  'configs' => $this->load->view('configurations_list', array('configs' => $configs), true), 
						  'pagination' => $pagination);
			$this->prepareScripts("/assets/js/jquery.js");
			$this->prepareScripts("/assets/js/collapse.js");
			parent::display($this->load->view('configuration_admin_list', $data, true));
		}
	}
	
	function configFilterForm ($filter, $render = true) {
		$form = array(
				'inputs' => array(
					'name' => array( 'required' => false),
					'title' => array( 'required' => false ),
					'values' => array( 'required' => false ),
					'default_value' => array( 'required' => false ),
					'form_control' => array( 'required' => false ),
					'group' => array('required' => false),
					'group_title' => array( 'required' => false ),
					'section' => array( 'required' => false),
					'section_title' => array( 'required' => false ),
					'section_comment' => array( 'required' => false ),
					'required' => array( 'required' => false )));
		
		if ($render) {
			
			$form['open_tag'] = form_open($this->uri->uri_string());
			$form['close_tag'] = form_close();
			
			if (array_key_exists('name', $filter)) { $value = $filter['name']; }
			else { $value = null; }
			$form['inputs']['name']['input'] = form_input('name', $value);
			$form['inputs']['name']['label'] = form_label($this->lang->line('configuration_filter_name_label'), 'name');
			$form['inputs']['name']['tip'] = $this->lang->line('configuration_filter_name_tip');
			
			if (array_key_exists('title', $filter)) { $value = $filter['title']; }
			else { $value = null; }
			$form['inputs']['title']['input'] = form_input('title', $value);
			$form['inputs']['title']['label'] = form_label($this->lang->line('configuration_filter_title_label'), 'title');
			$form['inputs']['title']['tip'] = $this->lang->line('configuration_filter_title_tip');
			
			if (array_key_exists('values', $filter)) { $value = $filter['values']; }
			else { $value = null; }
			$form['inputs']['values']['input'] = form_input('values', $value);
			$form['inputs']['values']['label'] = form_label($this->lang->line('configuration_filter_values_label'), 'values');
			$form['inputs']['values']['tip'] = $this->lang->line('configuration_values_tip');
			
			if (array_key_exists('default_value', $filter)) { $value = $filter['default_value']; }
			else { $value = null; }
			$form['inputs']['default_value']['input'] = form_input('default_value', $value);
			$form['inputs']['default_value']['label'] = form_label($this->lang->line('configuration_filter_default_value_label'), 'default_value');
			$form['inputs']['default_value']['tip'] = $this->lang->line('configuration_filter_default_value_tip');
			
			if (array_key_exists('form_control', $filter)) { $value = $filter['form_control']; }
			else { $value = null; }
			$form['inputs']['form_control']['input'] = form_dropdown('form_control', array(1 => 'text', 2 => 'textarea', 3 => 'checkbox', 4 => 'radiogroup', 5 => 'select'), $value);
			$form['inputs']['form_control']['label'] = form_label($this->lang->line('configuration_filter_form_control_label'), 'form_control');
			$form['inputs']['form_control']['tip'] = $this->lang->line('configuration_filter_form_control_tip');
			
			if (array_key_exists('group', $filter)) { $value = $filter['group']; }
			else { $value = null; }
			$form['inputs']['group']['input'] = form_dropdown('group', $this->Configurationmodel->getGroups(), $value);
			$form['inputs']['group']['label'] = form_label($this->lang->line('configuration_filter_group_label'), 'group');
			$form['inputs']['group']['tip'] = $this->lang->line('configuration_filter_group_tip');
			
			if (array_key_exists('group_title', $filter)) { $value = $filter['group_title']; }
			else { $value = null; }
			$form['inputs']['group_title']['input'] = form_input('group_title', $value);
			$form['inputs']['group_title']['label'] = form_label($this->lang->line('configuration_filter_group_title_label'), 'group_title');
			$form['inputs']['group_title']['tip'] = $this->lang->line('configuration_filter_group_title_tip');
			
			if (array_key_exists('section', $filter)) { $value = $filter['section']; }
			else { $value = null; }
			$form['inputs']['section']['input'] = form_input('section', $value);
			$form['inputs']['section']['label'] = form_label($this->lang->line('configuration_filter_section_label'), 'group');
			$form['inputs']['section']['tip'] = $this->lang->line('configuration_filter_section_tip');
			
			if (array_key_exists('section_title', $filter)) { $value = $filter['section_title']; }
			else { $value = null; }
			$form['inputs']['section_title']['input'] = form_input('section_title', $value);
			$form['inputs']['section_title']['label'] = form_label($this->lang->line('configuration_filter_section_title_label'), 'section_title');
			$form['inputs']['section_title']['tip'] = $this->lang->line('configuration_filter_section_title_tip');
			
			if (array_key_exists('section_comment', $filter)) { $value = $filter['section_comment']; }
			else { $value = null; }
			$form['inputs']['section_comment']['input'] = form_input('section_comment', $value);
			$form['inputs']['section_comment']['label'] = form_label($this->lang->line('configuration_section_comment_label'), 'section_comment');
			$form['inputs']['section_comment']['tip'] = $this->lang->line('configuration_section_comment_tip');
			
			if (array_key_exists('required', $filter)) { $value = $filter['required']; }
			else { $value = null; }
			$form['inputs']['required']['input'] = form_dropdown('required', array(0 => $this->lang->line('common_all'), 1 => $this->lang->line('common_yes'), 2 => $this->lang->line('common_no')));
			$form['inputs']['required']['label'] = form_label($this->lang->line('configuration_filter_required_label'), 'required');
			$form['inputs']['required']['tip'] = $this->lang->line('configuration_filter_required_tip');
			
			$form['controls'] = array(
				'submit' => form_submit('submit', $this->lang->line('configuration_save_label')), 
				'cancel' => form_submit('cancel', $this->lang->line('configuration_cancel_label')));
		}
		
		return $form;
	}
	
	function getConfigurationForm ($render = true) {
		
		$configs = $this->Configurationmodel->getObjectConfigs();
		
		$form = array('inputs' => array());
		
		while ($config = current($configs)) {
			
			$form['inputs'][$config->name] = array(
					'required' => ((int)$config->required > 1), 
					'section' => $config->section, 
					'section_title' => $config->section_title, 
					'section_comment' => $config->section_comment);
			
			if ($render) {
				
				if (!empty($this->messages['form'])) {
					$errors = $this->messages['form']['error'];
					$inputs = $this->messages['form']['inputs'];
				} else {
					$errors = array();
					$inputs = array();
				}
				
				if (!empty($inputs[$config->name])) { $config->value = $inputs[$config->name]; }
				
				$value = $config->value ? $config->value : $config->default_value;
				switch ($config->form_control) {
					case 2:
						$form['inputs'][$config->name]['input'] = form_textarea($config->name, $value);
						break;
					case 3:
						$form['inputs'][$config->name]['input'] = form_checkbox($config->name, $value); 
						break;
					case 4:
						break;
					case 5: 
						$form['inputs'][$config->name]['input'] = form_dropdown($config->name, $config->values, $value);
						break;
					default: //1
						$form['inputs'][$config->name]['input'] = form_input($config->name, $value);
				}
				
				$form['inputs'][$config->name]['label'] = form_label($config->title, $config->name);
				$form['inputs'][$config->name]['tip'] = $this->lang->line('configuration_' . $config->name . '_tip');
				if (in_array($config->name, $errors)) { $form['inputs'][$config->name]['error'] = $this->lang->line('configuration_error_msg_common'); }
			}
			$this->configuration[$config->name] = $config;
			next($configs);
		}
		
		if ($render) {
			
			$form['open_tag'] = form_open($this->uri->uri_string());
			$form['close_tag'] = form_close();
			
			$form['controls'] = array(
				'submit' => form_submit('submit', $this->lang->line('configuration_save_label')), 
				'cancel' => form_submit('cancel', $this->lang->line('configuration_cancel_label')));
		} 
		return $form;
	}
	
	
	function add ($config_id = null) {
		if ($this->input->post('submit')) {
			
			$form = $this->getAdminForm(false);
			$errorFlag = false;
			$error = array();
			$inputs = array();
			$dependsArray = array(0 => array(), 1 => array());
			
			foreach ($form['inputs'] as $key => $input) {
				if (!$this->input->post($key)) {
					
					if (!empty($dependsArray[0][$key])) {
						$errorFlag = true;
//						die('undepends: ' . $key . ' -- ' . $this->input->post($key));
						$error[] = $key;
						$error = array_merge($error, $dependsArray[0][$key]);
					}
					
					if ($input['required']) {
						$errorFlag = true;
						$error[] = $key;
					} elseif (!empty($input['required_if'])) {
						if (!is_array($input['required_if'])) { $input['required_if'] = array($input['required_if'] => false); }
						foreach ($input['required_if'] as $field => $filled) {
							if (array_key_exists($field, $inputs) && ($filled !== (bool)$inputs[$field])) {
								$errorFlag = true;
								die($field);
								$error[] = $key;
							} elseif(!array_key_exists($field, $inputs)) { 
								$dependsArray[(int)$filled][$field][] = $key;
							}
						}
					}
				} elseif (!empty($dependsArray[1][$key])) {
					$errorFlag = true;
//					die('depends: ' . $key);
					$error[] = $key;
					$error = array_merge($error, $dependsArray[1][$key]);
				}
				
				$inputs[$key] = $this->Configurationmodel->$key = $this->input->post($key);
			}
			
			if ($inputs['new_section']) { $this->Configurationmodel->section = $inputs['new_section']; }
			
			if ($errorFlag) {
				$this->setMessage($this->lang->line('configuration_error_filling_form'), 'error');
				$this->setMessage(array('error' => $error, 'inputs' => $inputs), 'form');
				redirect('configuration/add');
				return ;
			}
			
			if (empty($inputs['cid'])) { $inputs['order'] = $this->Configurationmodel->order = $this->Configurationmodel->checkOrder(); }

			if ($this->Configurationmodel->save()) {
				$this->setMessage($this->lang->line('configuration_save_success'), 'Success');
			} else {
				$this->setMessage($this->lang->line('configuration_save_failed'), 'Error');
			}
			redirect('/configuration');
		} else {
			$this->load->helper('form');

			if ($config_id) {
				$this->Configurationmodel->cid = $config_id;
				$this->Configurationmodel->get();
			}
			
			$content = $this->load->view('admin_config_form', $this->getAdminForm(), true);
		}
		parent::display($content);
	}
	
	
	function getAdminForm ($render = true) {
		
		$form = array(
				'inputs' => array(
					'name' => array('required' => true),
					'title' => array('required' => true),
					'values' => array('required' => false),
					'default_value' => array('required' => false),
					'form_control' => array('required' => true),
					'group' => array('required' => false, 'required_if' => array('new_group' => false)),
					'new_group' => array('required' => false),
					'group_title' => array('required' => false),
					'section' => array('required' => false, 'required_if' => array('new_section' => true)),
					'new_section' => array('required' => false),
					'section_title' => array('required' => false),
					'section_comment' => array('required' => false),
					'section_style' => array('required' => false),
					'order' => array('required' => false),
					'required' => array('required' => true)));
		
		if ($render) {
			
			if (array_key_exists('form', $this->messages)) {
				$errors = $this->messages['form']['error'];
				$inputs = $this->messages['form']['inputs'];
			} else {
				$errors = array();
				$inputs = array();
			}
			
			$form['open_tag'] = form_open($this->uri->uri_string());
			$form['close_tag'] = form_close();
			
			if (array_key_exists('name', $inputs)) { $this->Configurationmodel->name = $inputs['name']; }
			$form['inputs']['name']['input'] = form_input('name', $this->Configurationmodel->name);
			$form['inputs']['name']['label'] = form_label($this->lang->line('configuration_name_label'), 'name');
			$form['inputs']['name']['tip'] = $this->lang->line('configuration_name_tip');
			if (in_array('name', $errors)) { $form['inputs']['name']['error'] = $this->lang->line('configuration_error_msg_common'); }
			
			if (array_key_exists('title', $inputs)) { $this->Configurationmodel->title = $inputs['title']; }
			$form['inputs']['title']['input'] = form_input('title', $this->Configurationmodel->title);
			$form['inputs']['title']['label'] = form_label($this->lang->line('configuration_title_label'), 'title');
			$form['inputs']['title']['tip'] = $this->lang->line('configuration_title_tip');
			if (in_array('title', $errors)) { $form['inputs']['title']['error'] = $this->lang->line('configuration_error_msg_common'); }
			
			if (array_key_exists('values', $inputs)) { $this->Configurationmodel->values = $inputs['values']; }
			$form['inputs']['values']['input'] = form_textarea('values', $this->Configurationmodel->values);
			$form['inputs']['values']['label'] = form_label($this->lang->line('configuration_values_label'), 'values');
			$form['inputs']['values']['tip'] = $this->lang->line('configuration_values_tip');
			
			if (array_key_exists('default_value', $inputs)) { $this->Configurationmodel->default_value = $inputs['default_value']; }
			$form['inputs']['default_value']['input'] = form_input('default_value', $this->Configurationmodel->default_value);
			$form['inputs']['default_value']['label'] = form_label($this->lang->line('configuration_default_value_label'), 'default_value');
			$form['inputs']['default_value']['tip'] = $this->lang->line('configuration_default_value_tip');
			
			if (array_key_exists('form_control', $inputs)) { $this->Configurationmodel->form_control = $inputs['form_control']; }
			$form['inputs']['form_control']['input'] = form_dropdown('form_control', array(1 => 'text', 2 => 'textarea', 3 => 'checkbox', 4 => 'radiogroup', 5 => 'select'), $this->Configurationmodel->form_control);
			$form['inputs']['form_control']['label'] = form_label($this->lang->line('configuration_form_control_label'), 'form_control');
			$form['inputs']['form_control']['tip'] = $this->lang->line('configuration_form_control_tip');
			if (in_array('form_control', $errors)) { $form['inputs']['form_control']['error'] = $this->lang->line('configuration_error_msg_common'); }
			
			if (array_key_exists('group', $inputs)) { $this->Configurationmodel->form_control = $inputs['group']; }
			$form['inputs']['group']['input'] = form_dropdown('group', $this->Configurationmodel->getGroups());
			$form['inputs']['group']['label'] = form_label($this->lang->line('configuration_group_label'), 'group');
			$form['inputs']['group']['tip'] = $this->lang->line('configuration_group_tip');
			if (in_array('group', $errors)) { $form['inputs']['group']['error'] = $this->lang->line('configuration_error_msg_group'); }
			
			if (array_key_exists('new_group', $inputs)) { $new_group = $inputs['new_group']; }
			else { $new_group = null; }
			$form['inputs']['new_group']['input'] = form_input('new_group', $new_group);
			$form['inputs']['new_group']['label'] = form_label($this->lang->line('configuration_new_group_label'), 'new_group');
			$form['inputs']['new_group']['tip'] = $this->lang->line('configuration_new_group_tip');
			if (in_array('group', $errors)) { $form['inputs']['group']['error'] = $this->lang->line('configuration_error_msg_new_group'); }
			
			if (array_key_exists('group_title', $inputs)) { $group_title = $inputs['group_title']; }
			else { $group_title = null; }
			$form['inputs']['group_title']['input'] = form_input('group_title', $group_title);
			$form['inputs']['group_title']['label'] = form_label($this->lang->line('configuration_group_title_label'), 'group_title');
			$form['inputs']['group_title']['tip'] = $this->lang->line('configuration_group_title_tip');
			
			if (array_key_exists('section', $inputs)) { $this->Configurationmodel->section = $inputs['section']; }
			$form['inputs']['section']['input'] = form_dropdown('section', $this->Configurationmodel->getSections($this->group), $this->Configurationmodel->section);
			$form['inputs']['section']['label'] = form_label($this->lang->line('configuration_section_label'), 'group');
			$form['inputs']['section']['tip'] = $this->lang->line('configuration_section_tip');
			if (in_array('section', $errors)) { $form['inputs']['section']['error'] = $this->lang->line('configuration_error_msg_section'); }
			
			if (array_key_exists('new_section', $inputs)) { $new_section = $inputs['new_section']; }
			else { $new_section = null; }
			$form['inputs']['new_section']['input'] = form_input('new_section', $new_section);
			$form['inputs']['new_section']['label'] = form_label($this->lang->line('configuration_new_section_label'), 'new_section');
			$form['inputs']['new_section']['tip'] = $this->lang->line('configuration_new_section_tip');
			if (in_array('new_section', $errors)) { $form['inputs']['new_section']['error'] = $this->lang->line('configuration_error_msg_new_section'); }
			
			if (array_key_exists('section_title', $inputs)) { $section_title = $inputs['section_title']; }
			else { $section_title = null; }
			$form['inputs']['section_title']['input'] = form_input('section_title', $section_title);
			$form['inputs']['section_title']['label'] = form_label($this->lang->line('configuration_section_title_label'), 'section_title');
			$form['inputs']['section_title']['tip'] = $this->lang->line('configuration_section_title_tip');
			
			if (array_key_exists('section_comment', $inputs)) { $section_comment = $inputs['section_comment']; }
			else { $section_comment = null; }
			$form['inputs']['section_comment']['input'] = form_input('section_comment', $section_comment);
			$form['inputs']['section_comment']['label'] = form_label($this->lang->line('configuration_section_comment_label'), 'section_comment');
			$form['inputs']['section_comment']['tip'] = $this->lang->line('configuration_section_comment_tip');
			
			if (array_key_exists('section_style', $inputs)) { $section_style = $inputs['section_style']; }
			else { $section_style = null; }
			$form['inputs']['section_style']['input'] = form_input('section_style', $section_style);
			$form['inputs']['section_style']['label'] = form_label($this->lang->line('configuration_section_style_label'), 'section_style');
			$form['inputs']['section_style']['tip'] = $this->lang->line('configuration_section_style_tip');
			
			if (array_key_exists('order', $inputs)) { $this->Configurationmodel->order = $inputs['order']; }
			$form['inputs']['order']['input'] = form_input('order', $this->Configurationmodel->order);
			$form['inputs']['order']['label'] = form_label($this->lang->line('configuration_order_label'), 'order');
			$form['inputs']['order']['tip'] = $this->lang->line('configuration_order_tip');
			
			if (array_key_exists('required', $inputs)) { $this->Configurationmodel->required = $inputs['required']; }
			$form['inputs']['required']['input'] = form_dropdown('required', array(1 => $this->lang->line('common_yes'), 2 => $this->lang->line('common_no')));
			$form['inputs']['required']['label'] = form_label($this->lang->line('configuration_required_label'), 'required');
			$form['inputs']['required']['tip'] = $this->lang->line('configuration_required_tip');
			if (in_array('required', $errors)) { $form['inputs']['required']['error'] = $this->lang->line('configuration_error_msg_common'); }
			
			$form['controls'] = array(
				'submit' => form_submit('submit', $this->lang->line('configuration_save_label')), 
				'cancel' => form_submit('cancel', $this->lang->line('configuration_cancel_label')));
		}
		return $form;
	}
}
